﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;

namespace LJ.ColorPickerField
{
    class ColorPickerFieldControl: BaseFieldControl
    {
        protected TextBox myCustomText;
        protected TextBox myCustomText2;

        protected override string DefaultTemplateName
        {
            get
            {
                if (this.ControlMode == SPControlMode.Display)
                {
                    return base.DefaultTemplateName;
                }
                else
                {
                    return "ColorPickerFieldControl";
                }
                
            }
        }

        public override string DisplayTemplateName
        {
            get
            {
                return "ColorPickerFieldControlforDisplay";
            }
            set
            {
                base.DisplayTemplateName = value;
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            this.myCustomText = (TextBox)TemplateContainer.FindControl("myCustomText");
            this.myCustomText2 = (TextBox)TemplateContainer.FindControl("myCustomText2");
            if (this.ControlMode != SPControlMode.Display)
            {
                if (this.ControlMode != SPControlMode.New)
                {
                    myCustomText.Text = (string)this.ItemFieldValue;
                }
            }
            else
            {
                if (this.myCustomText2 != null)
                {
                    string fieldvalue = (string)this.ItemFieldValue;
                    if (fieldvalue != null)
                    {
                        myCustomText2.Text = fieldvalue; 
                    }
                }
            }

        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if ((this.ControlMode == SPControlMode.New) || (this.ControlMode == SPControlMode.Edit))
            {
                SPContext.Current.FormContext.OnSaveHandler += new EventHandler(MyCustomSave);
            }
        }

        protected void MyCustomSave(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                this.ItemFieldValue = myCustomText.Text;
                SPContext.Current.ListItem.Update();
            }
        }
    }
}
